package com.sgb.kjwl.view.ui.activity.transport;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;

import com.google.gson.JsonObject;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityTransportInquireByLetterBinding;
import com.sgb.kjwl.model.entity.pick.UserInquiryForTender;
import com.sgb.kjwl.utils.DialogFunction;
import com.sgb.kjwl.utils.DialogHelper;
import com.swgk.core.util.UserOperating;
import com.sgb.kjwl.view.ui.adapter.self.publish.ImageAdapter;
import com.swgk.core.dialog.RoundDialog;
import com.sgb.kjwl.view.widget.enterprise.AddContentListView;
import com.sgb.kjwl.viewmodel.transport.InquireByLetterViewModel;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.util.MToast;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: 王彬臣
 * @date: 2021/6/17
 * @Description: 物流函询提交页
 */
public class InquireByLetterActvity extends AppActivity {
    ActivityTransportInquireByLetterBinding mBinding;
    private ImageAdapter adapter;
    private List<String> urls;
    private List<File> fileList;
    public int imgTotal;
    private int currentImgNum;
    private List<String> uploadImgList = new ArrayList<>();
    private ArrayList<UserInquiryForTender.AddCustomListBean> customFieldListBeans = new ArrayList<>();//新增字段
    private List<UserInquiryForTender.FileListBean> fileImageList = new ArrayList<>();
    private int[] selectPosition = new int[1];
    List<LocalMedia> selectList = new ArrayList<>();
    private Map<String, Object> map = new HashMap<>();
    InquireByLetterViewModel mViewModel;
    int type;
    String userName;
    String userNo;
    String typeNo;
    String title;

    /***
     *
     * @param context
     * @param type     函询类型，普通货源 0，竞价货源1，车辆2，承运3
     * @param userName 货主/车主姓名
     * @param userNo   货主/车主NO
     * @param typeNo   函询类型，货源，车辆，承运NO
     * @param title    货源，承运 发货地->目的地  车辆 车牌号
     */
    public static void start(Context context,int type,String userName,String userNo,String typeNo,String title){
        Intent intent=new Intent(context,InquireByLetterActvity.class);
        intent.putExtra("type",type);
        intent.putExtra("userName",userName);
        intent.putExtra("userNo",userNo);
        intent.putExtra("typeNo",typeNo);
        intent.putExtra("title",title);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void initView() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_transport_inquire_by_letter);
        mBinding.setOnClick(this);
        mViewModel = new ViewModelProvider(this).get(InquireByLetterViewModel.class);
    }

    @Override
    protected void init() {
        type=getIntent().getIntExtra("type",0);
        userName=getIntent().getStringExtra("userName");
        userNo=getIntent().getStringExtra("userNo");
        typeNo=getIntent().getStringExtra("typeNo");
        title=getIntent().getStringExtra("title");


        urls = new ArrayList<>();
        fileList = new ArrayList<>();
        adapter = new ImageAdapter(this, null, null, 5);
        mBinding.recyclerView.setLayoutManager(new GridLayoutManager(this, 4));
        mBinding.recyclerView.setAdapter(adapter);
        mViewModel.uploadRefresh.observe(this,this::uploadRefresh);
        mBinding.reiverName.setText(userName);

        mViewModel.saveSuccess.observe(this,s -> {
            finish();
        });
    }

    /**
     * 设置新增按钮是否可点击
     *
     * @param useable true可用
     */
    public void setAddUseable(boolean useable) {
        if (useable) {
            mBinding.ivAddAns.setAlpha(1);
            mBinding.ivAddAns.setClickable(true);
        } else {
            mBinding.ivAddAns.setAlpha(0.5f);
            mBinding.ivAddAns.setClickable(false);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_submit:
                if (!ClickUtils.isDoubleClick()) {
                    if (TextUtils.isEmpty(mBinding.cfkEdit.getEditContent()) || mBinding.cfkEdit.getEditContent().length() < 5) {
                        MToast.showLongToast(getApplicationContext(), "请输入疑问事项最少5个字最多200字");
                        return;
                    }
                    if (!checkItemInput(true)) {
                        return;
                    }
                    if(userNo.equals(UserOperating.getInstance().getUserNo())){
                        new RoundDialog.Builder(this)
                                .title("提示")
                                .content("自己不能对自己发起函询")
                                .confirm("我知道了")
                                .singleBtn(true)
                                .contentGravity(Gravity.CENTER)
                                .cancelable(false)
                                .show();
                        return;
                    }
                    if (adapter.getFileList().size() != 0) {
                        uploadImgList.clear();
                        imgTotal = adapter.getFileList().size();
                        mViewModel.uploadMutiFileModel(this, adapter.getFileList().get(currentImgNum), currentImgNum + 1);
                    } else {
                        uploadData(adapter.getUrls(), 1);
                    }
                }
                break;
            case R.id.iv_add_ans:
                if (mBinding.rootLayout.getChildCount() < 5) {
                    setAddUseable(false);
                    if (mBinding.rootLayout.getChildCount() > 0) {
                        if (checkItemInput(true)) {
                            AddContentListView pickDetailListView = new AddContentListView(this);
                            mBinding.rootLayout.addView(pickDetailListView);
                            pickDetailListView.OnInputContent(new AddContentListView.IInputContent() {
                                @Override
                                public void hasContent() {
                                    if (mBinding.rootLayout.getChildCount() < 5)
                                        setAddUseable(true);
                                }

                                @Override
                                public void hasNoContent() {
                                    setAddUseable(false);
                                }
                            });
                            pickDetailListView.setItemChildCLickListener(new AddContentListView.ItemChildCLickListener() {
                                @Override
                                public void deletePos() {
                                    mBinding.rootLayout.removeView(pickDetailListView);
                                    setAddUseable(checkItemInput(false));
                                }
                            });
                        }
                    } else {
                        AddContentListView pickDetailListView = new AddContentListView(this);
                        mBinding.rootLayout.addView(pickDetailListView);
                        pickDetailListView.OnInputContent(new AddContentListView.IInputContent() {
                            @Override
                            public void hasContent() {
                                if (mBinding.rootLayout.getChildCount() < 5)
                                    setAddUseable(true);
                            }

                            @Override
                            public void hasNoContent() {
                                setAddUseable(false);
                            }
                        });
                        pickDetailListView.setItemChildCLickListener(new AddContentListView.ItemChildCLickListener() {
                            @Override
                            public void deletePos() {
                                mBinding.rootLayout.removeView(pickDetailListView);
                                setAddUseable(checkItemInput(false));
                            }
                        });
                    }

                } else {
                    MToast.showLongToast(getApplicationContext(), "最多添加5条");
                }
            break;

        }
    }

    private boolean checkItemInput(boolean isShowToast) {
        for (int i = 0; i < mBinding.rootLayout.getChildCount(); i++) {
            AddContentListView pickLetterListView = (AddContentListView) mBinding.rootLayout.getChildAt(i);
            if (pickLetterListView.getViewContent()) {
                if (isShowToast) {
                    DialogHelper.showSingleDialog(this, "", "新增的标题与内容全部填写", "确定", false, new DialogFunction() {
                        @Override
                        public void normalRoundDialog() {

                        }
                    });

                }
                return false;
            }
        }
        return true;
    }

    //提交数据
    private void uploadData(List<String> urls, int mType) {
        //拼接图片url
        for (int i = 0; i < urls.size(); i++) {
            UserInquiryForTender.FileListBean fileListBean = new UserInquiryForTender.FileListBean();
            int picI = i + 1;
            fileListBean.setName("第" + picI + "张图片");
            fileListBean.setFileUrl(urls.get(i));
            if (mType == 0) {
                fileImageList.add(fileListBean);
            }
        }
        for (int i = 0; i < mBinding.rootLayout.getChildCount(); i++) {
            AddContentListView pickLetterListView = (AddContentListView) mBinding.rootLayout.getChildAt(i);
            customFieldListBeans.add(pickLetterListView.getContent());
        }
        if(type==0||type==1) {
            map.put("goodsSourceNo", typeNo);
        }else if(type==2){
            map.put("driverNo", typeNo);
        }else{
            map.put("carrierNo", typeNo);
        }
        map.put("pattern",type);
        map.put("title",title);
        map.put("question",mBinding.cfkEdit.getEditContent());
        if(!TextUtils.isEmpty(mBinding.cfkEdit2View.getEditContent())){
            map.put("understanding",mBinding.cfkEdit2View.getEditContent());
        }
        if(!TextUtils.isEmpty(mBinding.cfkEdit3View.getEditContent())){
            map.put("request",mBinding.cfkEdit3View.getEditContent());
        }
        if (customFieldListBeans != null && customFieldListBeans.size() > 0) {
            JsonObject field = new JsonObject();
            for (UserInquiryForTender.AddCustomListBean diy : customFieldListBeans) {
                field.addProperty(diy.getName(), diy.getContent());
            }
            map.put("addField", field.toString());
        }
        map.put("fileList",fileImageList);
        map.put("answererNo",userNo);
        map.put("answerer",userName);
        mViewModel.saveUserInquiry(this,map);
    }

    //图片单张上传
    public void uploadRefresh(String url) {
        uploadImgList.add(url);
        if (currentImgNum + 1 == imgTotal) {
            uploadData(uploadImgList, 0);
        } else {
            currentImgNum++;
            mViewModel.uploadMutiFileModel(this, adapter.getFileList().get(currentImgNum), currentImgNum + 1);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {// 图片结果回调
                selectList = PictureSelector.obtainMultipleResult(data);
                fileList.clear();
                urls.clear();
                for (LocalMedia localMedia : selectList) {
                    File file = new File(localMedia.getRealPath());
                    fileList.add(file);
                    urls.add(localMedia.getRealPath());
                }
                adapter.setDatas(selectList, urls);
                adapter.setFileList(fileList);
            }
        }
    }
}
